import CommonUtil from '../utils/common'
import ArrayUtil from '../utils/array'
import { cloneDeep, omitBy } from 'lodash'
import URLUtil from '../utils/url'
import clone from 'clone'

const MICRO_APP_REGEXP = /{microapp:[a-z, A-Z,-,/]+}/,
  PATH_REGEXT = /\/:{path:[a-z, A-Z,-, 0-9]+}/,
  PLACEHOLDER_REGEXP = /{[a-z, A-Z,-]+:[a-z, A-Z,-]+}/g,
  ROOT_REGEXP = /\/{root:[a-z, A-Z,-,/]+}/

export default (dataList, router) => {
  const routeMap = router.flatRoutes(clone(router.getRouteConfig('pc'))),
    actionMap = {}, routePathMap = [], routeList = [],
    menuList = [], rootMap = {}, rootList = router.getRootList(),
    defaultRootStaticMenuList = []

  // 默认根路由
  let defaultRoot = null
  rootList.map(root => {
    rootMap[root.path] = root
    const root_children = root.children || []
    root.children = []
    const routes = router.flatRoutes(clone(root_children))
    Object.keys(routes).map(k => {
      root.children.push(routes[k])
    })
    if (root.path == '/' || root.path == '') {
      defaultRoot = root
      buildLocalRouteMenu(root_children, root).map(menu => {
        defaultRootStaticMenuList.push(menu)
      })
    }
  })

  // 缓存功能权限
  dataList.map(data => {
    if (data.type === '3') {
      actionMap[data.parentId] = actionMap[data.parentId] || []
      actionMap[data.parentId].push(data.code.split(':').pop())
    }
  })

  dataList.map(data => {
    let url = data.uri?.split('?')[0],
      menu = {
        id: data.id,
        parentId: data.parentId,
        meta: {
          key: data.id,
          id: data.id,
          parentId: data.parentId,
          title: data.name,
          hidden: data.type == '3' ? true : CommonUtil.toBool(data.hidden),
          icon: data.icon,
          type: data.type
        }
      }
    data.uri && data.target != '4' && (menu.query = URLUtil.getURLParams(data.uri) || {})
    data.target == '3' && (menu.meta.target = '_blank')
    data.target == '2' && (menu.meta.target = 'iframe')

    menuList.push(menu)

    if (!url) {
      return
    }
    menu.path = url

    if (data.target == '4') {
      // 微应用
      const config = JSON.parse(data.uri)
      menu.path = `/${config.code}${config.path}`
      delete menu.meta.key
      if (routePathMap[config.root]?.[config.code]) {
        return
      }
      const route = router.buildMicroApp(config, menu.meta)
      if (!route) {
        return
      }
      menu.query = config.params || {}
      rootMap[config.root].children.push(route)
      route.meta._parent = rootMap[config.root]
      routePathMap[config.root] = routePathMap[config.root] || {}
      routePathMap[config.root][config.code] = true
      return
    }

    if (!menu.path.startsWith('/')) {
      return
    }

    // 匹配 root
    let match_root = menu.path.match(ROOT_REGEXP),
      path_match = menu.path.match(PATH_REGEXT),
      routePath = menu.path,
      root = null

    if (match_root) {
      // 匹配到根路由参数
      // const match_root_split = match_root[0].substring(1, match_root[0].length - 1).split(':')
      // routePath = menu.path.substring(0, path_match.index) + '/:path*'
      // menu.path = menu.path.substring(0, match_root.index) + '/' + path_match_split[1]
    }

    if (!match_root) {
      root = rootList.find(r => routePath.startsWith(`${r.path}/`) && r.path != '/')
    }

    !root && (root = defaultRoot)

    let route = routeMap[routePath]

    if (path_match) {
      // 匹配到动态路由
      delete menu.meta.key
      const path_match_split = path_match[0].substring(3, path_match[0].length - 1).split(':')
      menu.path = menu.path.replace(PATH_REGEXT, `/${path_match_split[1]}`)
      return
    }

    if (menu.query.menuId) {
      // 先查找
      menu.meta.key = `${menu.path}/menu/${menu.query.menuId}`
      menu.path = `${menu.path}/menu/${menu.query.menuId}`
      return
    }

    if (!route) {
      console.error(`找不到对应路由配置信息:${routePath}`)
      return
    }
    // 合并菜单 meta 到路由
    CommonUtil.merge(route.meta, menu.meta)

    // 转存在 path 路径上配置的参数
    menu.query && (route.query = menu.query)

    // 添加功能权限
    route.meta.authorize = actionMap[route.meta.id] || []

    // 移除该路由下没有path的子节点
    if (route.children) {
      route.children = route.children.filter(child => child.path)
    }
    root.children.push(route)
  })

  // array 转 tree
  let { nodeList, nodeMap } = ArrayUtil.toTree(menuList, 'id', 'parentId')

  // defaultRoot.children = defaultRootStaticMenuList.concat(defaultRoot.children)
  nodeList = defaultRootStaticMenuList.concat(nodeList)

  // 设置默认根路由的重定向地址
  defaultRoot.children.find(child => {
    return setDefaultRedirect(defaultRoot, child)
  })
  return { rootList, menuList: nodeList, menuMap: nodeMap }
}

/**
 * 构建本地注册的路由菜单
 * @param {*} router
 */
function buildLocalRouteMenu (children, parent) {
  children.map(child => {
    Object.assign(child, {
      id: child.path,
      parentId: parent.path || null,
      _parent: parent
    })
    child.meta = Object.assign(child.meta || {}, {
      key: child.path,
      id: child.path,
      parentId: parent.path || null
    })
    if (child.path.indexOf('/:') != -1) {
      child.meta.hidden = true
    }
    child.children && buildLocalRouteMenu(child.children, child)
  })
  return children
  // const menuList = children.map(child => {
  //   child.meta.id = child.path
  //   child.meta.parentId = child.meta._parent?.path || null

  //   // 构建菜单数据
  //   return {
  //     id: child.path,
  //     parentId: child.meta._parent?.path || null,
  //     path: child.path,
  //     meta: {
  //       id: child.path,
  //       parentId: child.meta._parent?.path || null,
  //       ...cloneDeep(child.meta)
  //     }
  //   }
  // })
  // const { nodeList, nodeMap } = ArrayUtil.toTree(menuList, 'id', 'parentId')
  // // 只返回没有上级节点的菜单数据
  // return nodeList
}

function setDefaultRedirect (root, menu) {
  if (root.redirect) {
    return true
  }
  if (!menu.meta?.hidden && menu.path && menu.path.indexOf('/:') == -1) {
    root.redirect = menu.path
    return true
  } else if (menu.children) {
    menu.children.find(child => {
      return setDefaultRedirect(root, child)
    })
  }
  return false
}

function getDefaultRedirect (route) {

}

function hideChildren (routeList) {
  routeList.map(r => {
    if (r.children) {
      if (r.children.length == 0) {
        r.hideChildrenInMenu = true
      } else {
        // 下级节点不为功能菜单并且下级节点没有要显示的菜单
        const c = r.children.find(c => {
          return c.meta?.type != '3' && !c.hidden
        })
        !c && (r.hideChildrenInMenu = true)
      }
    }
    hideChildren(r.children || [])
  })
}
